package com.nintendo.interceptors;

import com.nintendo.exceptions.GraceException;
import com.nintendo.result.ResponseStatusEnum;
import com.nintendo.utils.IPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Objects;

import static com.nintendo.base.BaseInfoProperties.USER_MOBILE_CODE;

@Component
public class SmsConfigInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestIp = IPUtil.getRequestIp(request);
        Object userMobileCodeObj = redisTemplate.opsForValue().get(USER_MOBILE_CODE+requestIp);
        System.out.println("userMobileCodeObj=====>"+userMobileCodeObj);
        if(Objects.nonNull(userMobileCodeObj)){
            GraceException.display(ResponseStatusEnum.USER_MOBILE_CODE_IS_OFTEN);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
